using System.Text;

namespace NetduinoRobot.Common
{
    /// <summary>
    /// Helper Class for CommandReadWrite
    /// Written by: Salvador Richter
    /// Appache License Version 2.0 
    /// </summary>
    public class CommandHelper
    {
        public static readonly char CommandSeparator = '#';
        public static readonly char ParameterSeparator = ';';
        public static readonly char ParameterSeparatorDescription = ',';
        public static readonly char ParameterSeparatorMultiValue = '#';

        private readonly int StartTagLength = 15; //<cmd len=00000>
        private readonly int EndTagLength = 6; //</cmd>
        private readonly string EndTag = "</cmd>";
        private readonly string StartTagPrefix = "<cmd len=";

        /// <summary>
        /// wraps a command in an xml envelope, tis envelope contains the commands length 
        /// as len param, where len is total length including start and end tag
        /// </summary>
        /// <param name="command">command to be wrapped in envelope</param>
        /// <returns>command wrapped in envelope</returns>
        public string CreateEnvelope(string command)
        {
            int len = command.Length + StartTagLength + EndTagLength;
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.Append(StartTagPrefix);
            // int.ToString does not take the "dx" param in MF
            if (len < 10000) { sBuilder.Append('0'); }
            if (len < 1000) { sBuilder.Append('0'); }
            if (len < 100) { sBuilder.Append('0'); }
            // cmd wont be less than 21 digits
            sBuilder.Append(len);
            sBuilder.Append('>');
            sBuilder.Append(command);
            sBuilder.Append(EndTag);
            return sBuilder.ToString();
        }
    }
}
